<template>
  <div class="task-card" shadow="hover">
    <!-- 连接器附加组件 -->
    <el-row class="task-card-main" type="flex" justify="space-between">
      <el-row type="flex">
        <el-row class="task-card-content" type="flex">
          <h2 class="task-card-title" >
            
            <el-tooltip class="item" effect="dark" :content="getCardNameLabel(taskCard)" :disabled="!isCardNameOverflow" placement="top">
              <p :class="['task-card-name',taskCard.enabled == 0 && 'task-card-enabled']" ref="parentNameWidth"><span ref="childNameWidth">{{getCardNameLabel(taskCard)}}</span></p>
            </el-tooltip>    
            <el-tooltip class="item" effect="dark" :content="$t('task.setting.taskTypeSetting.flow.components.tip5')" placement="top">
              <span class="task-card-disable" v-if="taskCard.enabled == 0">
                {{$t('common.base.disabled')}}
              </span>
            </el-tooltip>
            
            <ConnectorTag :card="taskCard">
            </ConnectorTag>
            
          </h2>
          <el-row class="task-card-others">
            <div class="task-card-others-info">
              {{$t('event.setting.serviceEventTypeSetting.flow.component.cardItem.label1')}}： 
              <span class="pointer" v-if="taskCard.notNullFlow || (taskCard.stateCanEdit && taskCard.stateCanEdit.length>0)">{{$t('common.base.haveSet')}} </span>
              <span class="pointer" v-else>{{$t('common.base.notSet')}} </span>
              <i class="iconfont icon-bianji1 pointer" @click="onSetRules"></i>
            </div>
            <div  class="task-card-others-info" @click="onSetEditpermiss">
              {{$t('event.setting.serviceEventTypeSetting.flow.component.cardItem.label2')}}：
              <span class="pointer see-role">{{$t('event.setting.serviceEventTypeSetting.flow.component.cardItem.des1')}} </span>
              <i class="iconfont icon-bianji1 pointer"></i>
            </div>
            <div  class="task-card-others-info">
              {{$t('event.setting.serviceEventTypeSetting.flow.component.cardItem.label3')}}：
              <span v-if="taskCard.inputType == 'single'">{{$t('common.base.onceTime')}}</span> <span v-if="taskCard.inputType == 'multiple'">{{$t('common.base.moreTime')}}</span>
            </div>
          </el-row>
        </el-row >
      </el-row>
      <i v-if="!isCardListSetting" class="iconfont icon-tuozhuaipaixu drag-icon"></i>
    </el-row>
    <el-row class="task-card-opearte" type="flex">
      <!-- 连接器附加组件有编辑和重命名 没有预览 -->
      <template v-if="isConnectorCard(taskCard)">
        <div class="connector-list-view-card-item-footer-left">
          <el-dropdown placement="top">
            <i class="icon-diandiandian iconfont">{{t('common.base.moreOperator')}}</i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <div @click="editCardName">
                  <i class="iconfont icon-edit-square"></i>
                  {{t('common.base.rename')}}
                </div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div @click="delTaskCard">
                  <i class="iconfont icon-delete"></i>
                  {{t('common.base.delete')}}
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div class="task-card-opearte-del" @click="editCard">
        <i class="iconfont icon-edit-square">{{$t('common.base.edit')}}</i>
      </div>
      </template>
      <template v-else>
        <div class="task-card-opearte-del" @click="delTaskCard">
          <i class="iconfont icon-delete">{{$t('common.base.delete')}}</i>
        </div>
        <div class="task-card-opearte-modify" @click="previewCard(taskCard)">
          <i class="iconfont icon-eye-fill">{{$t('common.base.preview')}}</i>
        </div>
      </template>
    </el-row>

    <!-- start 设置使用规则 -->
    <use-rules-dialog
      :task-card="taskCard"
      :task-type-id="taskTypeId"
      :visiable.sync="isShowRulesModal"
      @onClose="onCloseRules"
      @update="updateRulesList"/>
    <!-- end 设置使用规则 -->

    <!-- start 设置使用权限 -->
      <card-select-user-dialog
        :task-card="taskCard"
        :task-type-id="taskTypeId"
        :visiable.sync="isShowEditpermissModal"
        @onClose="onCloseEditpermiss"
        @update="updateRulesSetting"
      />
    <!-- end 设置使用权限 -->

    <!--start 预览组件 -->
    <preview-card-dialog ref="previewDialog" :fields="fields"></preview-card-dialog>
    <!--end 预览组件 -->

    <!-- 编辑连接器名称 -->
    <ConnectorListViewCreateDialog
        :title="$t('common.connector.editConnector')"
        :value="formValue"
        :visible="isShowEditConnectorNameModal"
        :fields="CreateConnectorModalFields"
        :is-connector="true"
        isShowSelectLanguage
        @close="onDialogCloseHandler"
        @confirm="onDialogConfirmHandler"
        @input="onDialogUpdateHandler"
    >
    </ConnectorListViewCreateDialog>
  </div>
</template>

<script>
import _ from 'lodash';
/** api */
import * as SettingTaskApi from '@src/api/SettingTaskApi';
import { getConnectorName, updateConnectorName } from '@src/modules/connector/api';
/** component */
import UseRulesDialog from '../components/TaskCard/UseRulesDialog';
import CardEditpermissDialog from '../components/TaskCard/cardEditpermissDialog';
import { ConnectorListViewCreateDialog } from '@src/modules/connector/view/list/components';
// components
import PreviewCardDialog from '../../../components/PreviewCardDialog';
import { CardNameLabelEnum } from '@model/enum/LabelEnum'
import CardSelectUserDialog from './TaskCard/CardSelectUserDialog.vue';
import ConnectorTag from '@src/modules/setting/components/connectorTag/index.vue';
/* service */
import { isConnectorCard } from '@service/CardService';
import { message } from '@src/util/message'
import { t } from '@src/locales'

const CreateConnectorModalFields = [
  {
    fieldName: 'name',
    formType: 'text',
    displayName: t('common.base.name'),
    placeHolder: t('common.placeholder.inputName'),
    isNull: 0,
    maxlength: 20
  },
  {
    fieldName: 'description',
    formType: 'textarea',
    displayName: t('common.base.explain'),
    placeHolder: t('common.connector.fields.description.placeholder1'),
    isNull: 1,
    maxlength: 500
  }
]

export default {
  name: 'task-card-item',
  props: {
    taskCard: {
      type: Object,
      default: () => ({})
    },
    index: {
      type: Number   
    },
    taskTypeId: {
      type: String,
    },
    taskTypeName: {
      type: String,
      default: ''
    },
    from: {
      type: String,
      default: ''
    }
  },
  computed: {
    connectorInfo() {
      let res = {}
      try {
        const config = this.taskCard?.config
        if(config) {
          res = JSON.parse(config) || {}
          return res.connectorInfo || {}
        }
      } catch (error) {
        console.warn('connectorInfo', error)
      }
      return res
    },
    isCardListSetting() {
      return this.from === "cardListSetting";
    }
  },
  data() {
    return {
      fields:[],
      isShowEditpermissModal: false,
      isShowRulesModal: false, // 设置使用规则
      isCardNameOverflow: false,
      isShowCreateConnectorModal: false,
      isShowEditConnectorNameModal: false,
      CreateConnectorModalFields,
      formValue: {},
    }
  },
  mounted() {
    this.initOverflow()
  },
  methods: {
    async editCardName() {
      try {
        const res = await getConnectorName(this.connectorInfo)
        if(res.status == 0){ 
          const { data = {} } = res
          this.isShowEditConnectorNameModal = true
          this.formValue.id = data.id
          this.formValue.name = data.connectorName || ''
          this.formValue.description = data.connectorRemarks || ''

          this.formValue.titleLanguage = data.titleLanguage || {}
          this.formValue.descLanguage = data.descLanguage || {}
        } else {
          message.error(res.message)
        }
      } catch(error) {
        console.log(error)
      }
    },
    resetFormValue(){
      this.formValue = {
        id: '',
        name:'',
        description:'',
        titleLanguage: {},
        descLanguage: {}
      }
    },
    onDialogCloseHandler(){
      this.isShowEditConnectorNameModal = false
      this.resetFormValue()
    },
    onDialogConfirmHandler(){
      const params = {
        id: this.formValue.id,
        connectorName: this.formValue.name,
        connectorRemarks: this.formValue.description,
        titleLanguage: this.formValue.titleLanguage,
        descLanguage: this.formValue.descLanguage
      }
      updateConnectorName(params).then(res=>{
        if(res.status == 0){
          // 更新附加组件列表
          this.$emit('finish')
          message.success(this.$t('common.base.tip.modifySuccess'))
          this.onDialogCloseHandler()
        }else{
          message.error(res.message)
        }
      })
    },
    onDialogUpdateHandler(info) {
      let { fieldName,newValue } = info
      if( !fieldName )return;
      this.formValue[fieldName] = newValue
    },
    // 获取附加组件标题的多语言label
    getCardNameLabel(item) {
      const { name, cardNameLanguage } = item
      const locale = this.$i18n.locale
      return cardNameLanguage?.locale || CardNameLabelEnum[name] || name
    },
    isConnectorCard,
    // 初始化溢出tips
    initOverflow() {
      this.$nextTick(()=> {
        this.isCardNameOverflow = this.$refs?.parentNameWidth?.offsetWidth < this.$refs?.childNameWidth?.offsetWidth
      })
    },
    // 删除组件
    delTaskCard() {
      this.$confirm(this.$t('common.base.tip.areYouWantDeleteIt', {data1:this.taskCard.name}), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      }).then(() => {
        console.log(this.taskCard)
        this.$emit('deleteCard', this.index)

      });
    },
    // 设置使用规则
    onSetRules() {
      this.isShowRulesModal = true;
    },
    onCloseRules() {
      this.isShowRulesModal = false;
    },
    // 编辑权限
    onSetEditpermiss() {
      this.isShowEditpermissModal = true;
    },
    onCloseEditpermiss() {
      this.isShowEditpermissModal = false;
    },
    // 更新taskCard
    updatetaskCard(obj) {
      this.$emit('updateAttr', obj);
    },
    // 新的权限规则
    updateRulesSetting(isSetObject){
      this.updatetaskCard({
        isSetObject
      });
    },

    // 更新使用规则
    updateRulesList(flow, stateCanEdit){
      this.updatetaskCard({
        notNullFlow: flow,
        stateCanEdit
      });
      this.onCloseRules();
    },

    // 更新使用权限
    updateRolesList(authInfo){
      this.updatetaskCard({
        authInfo
      });
      this.onCloseEditpermiss();
    },
    getCardFieldsReq(card) {
      const params = {
        cardId:card.id,
        isFromSetting: false
      }
      SettingTaskApi.getAddCardFields(params)
        .then((res) => {
          this.fields = res; 
        }).catch((error) => {
          console.log(error);
        });
    },
    // 预览组件
    previewCard(card) {
      this.getCardFieldsReq(card)
      this.$refs.previewDialog.openDialog();
    },
    // 编辑连接器附加组件
    editCard() {
      this.$emit('edit', this.taskCard)
    },
    // 保存编辑连接器附加组件事件
    finish() {
      this.$emit('finish')
    },
  },
  components: {
    [UseRulesDialog.name]: UseRulesDialog,
    [CardEditpermissDialog.name]: CardEditpermissDialog,   
    [PreviewCardDialog.name]: PreviewCardDialog,   
    [CardSelectUserDialog.name]: CardSelectUserDialog,
    ConnectorListViewCreateDialog,
    ConnectorTag
  }
}
</script>

<style lang="scss" scoped>
.task-card{
    position: relative;
    cursor: move;
    width: 358px;
    height: 159px;
    background: #FFFFFF;
    border-radius: 4px;
    box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.04); 
    &:hover{
        box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.12);
    }
    .i-link {
      position: absolute;
      right: 8px;
      top: 8px;
      width: 47px;
      height: 20px;
    }
    .task-card-main{
        display: flex;
        height: calc(100% - 32px);
        padding: 16px 20px;
        .drag-icon{
            font-size: 12px;
            display: none;
        }

        .task-card-content{
            flex-direction: column;
            justify-content: space-between;
            height: 100%;
            .task-card-title{
                display: flex;
                justify-content: flex-start;
                margin-top: 0;
                .task-card-name{
                    display: inline-block;
                    max-width: 230px;
                    margin-bottom: 0;
                    @include text-ellipsis;
                    word-break: break-all;
                    padding-right: 12px;
                    font-size: 16px;
                    color: #333333;
                    line-height: 22px;
                    cursor: pointer;
                }
                .setting-card-connector-tag-container {
                  padding-left: 0;
                }
                .task-card-enabled{        
                    max-width: 200px;
                    padding-right: 0px;
                    margin-right: 12px;          
                }
                .task-card-disable{
                    width: 54px;
                    height: 22px;
                    line-height: 22px;
                    font-size: 12px;
                    font-weight: 500;
                    text-align: center;
                    color: #999999;
                    background: rgba(153, 153, 153, 0.2);
                    border-radius: 12px;
                    border: 1px solid rgba(191, 191, 191, 0.2);
                    cursor: pointer;
                }
            }

            .task-card-others{
                i{
                    font-size: 12px;
                    color: #666;
                    &:hover{
                        color: $color-primary;
                    }
                }
                &-info{
                    margin-bottom: 4px;
                    font-size: 12px;
                    color: #666666;
                    span{
                        color: #333333;
                        margin-right: 8px;
                    }
                    &:last-child{
                        margin-bottom: 0;
                        margin-top: 4px;
                    }
                    .see-role{
                        color: $color-primary;
                    }
                }
            }
        }
    }
    .task-card-opearte{
        height: 32px;
        border-top: 1px solid#F5F5F5;
        & > div {
            cursor: pointer;
            flex: 1;
            text-align: center;
            line-height: 32px;
            color: #999999;
            i{
              font-size: 12px;
              &::before{
                margin-right: 8px;
              }
            }
        }
        .task-card-opearte-del{
           border-right: 1px solid#F5F5F5; 
            &:hover{
                color: $color-danger;
            }
        }
        .task-card-opearte-modify{
            &:hover{
                color: $color-primary;
            }
        }
    }
    &:hover{
        .drag-icon{
            display: block;
        }
    }
}

.pointer{
    cursor: pointer;
}
@media screen and (max-width: 1920px) {
  .task-card-item {
    width: calc(25% - 12px);
  }
}
@media screen and (max-width: 1680px) {
  .task-card-item {
    width: calc(33.3% - 12px);
  }
}
@media screen and (max-width: 1440px) {
  .task-card-item {
    width: 328px;
  }
}
</style>